package lwk.forkjoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.function.LongBinaryOperator;
import java.util.stream.LongStream;

/**
 * @author:lwk
 * @create: 2022-08-19 22:19
 * @Description:
 */
public class TestForkJoin {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        test1(); // sum = 500000000500000000 time:373
        test2(); // sum = 500000000500000000 time:150
        test3(); // sum = 500000000500000000 time:101

    }

    // 传统
    private static void test1() {
        long sum = 0L;
        long start = System.currentTimeMillis();
        for (long i = 0L; i <= 10_0000_0000; i++) {
            sum += i;
        }
        long end = System.currentTimeMillis();
        System.out.println("sum = "+sum +" time:"+(end-start));
    }

    // ForkJoinTask
    private static void test2() throws ExecutionException, InterruptedException {
        //ForkJoin实现
        ForkJoinPool forkJoinPool = new ForkJoinPool();//实现ForkJoin 就必须有
        //ForkJoinPool的支持
        ForkJoinTask<Long> task = new ForkJoinDemo(0L,10_0000_0000L);//参数为起

        long start = System.currentTimeMillis();
        //始值与结束值
        ForkJoinTask<Long> result = forkJoinPool.submit(task);
        long sum = result.get();
        long end = System.currentTimeMillis();
        System.out.println("sum = "+sum +" time:"+(end-start));
    }

    private static void test3() {
        //Java 8 并行流的实现
        long start = System.currentTimeMillis();
        long sum = LongStream.rangeClosed(0L, 10_0000_0000L).parallel().reduce(0, new LongBinaryOperator() {
            @Override
            public long applyAsLong(long left, long right) {
                return left + right;
            }
        });
        long end = System.currentTimeMillis();
        System.out.println("sum = "+sum +" time:"+(end-start));
    }

}
